import {
  Body,
  Controller,
  Post,
  Res,
  UploadedFile,
  UseInterceptors
} from "@nestjs/common";
import { OssFileService } from "./oss-file.service";
import * as fs from "node:fs";
import { createReadStream } from "fs";
import { Readable } from "stream";
import { FileInterceptor } from "@nestjs/platform-express";

@Controller("oss-file")
export class OssFileController {
  constructor(private readonly ossFileService: OssFileService) {
  }

  @Post("/count")
  async downloadCount(@Body() body: any) {
    const { username } = body;
    return await this.ossFileService.downloadOssCount(username);
  }

  @Post("/download")
  async downloadFile(@Body() body: any, @Res() res: any) {
    try {
      const { path } = body;
      let blob = await this.ossFileService.downloadOssFile(path);
      const buffer = Buffer.from(blob);
      const stream = Readable.from(buffer);

      res.set({
        "Content-Type": "application/octet-stream",
        "Content-Length": buffer.length,
        "Content-Disposition": "attachment; filename=\"downloaded_file\"",
        "Access-Control-Expose-Headers": "Content-Disposition"
      });

      stream.pipe(res);
    } catch (e) {
      return { status: 500, message: "文件不存在" };
    }
  }

  @Post("/upload")
  @UseInterceptors(FileInterceptor("fileBuffer"))
  async uploadFile(@Body() body: any, @UploadedFile() fileBuffer: Express.Multer.File) {
    const { fileName, type, user } = body;
    let buffer: Buffer;
    if (type !== "count") {
      buffer = await new Promise<Buffer>((resolve, reject) => {
        const chunks: Uint8Array[] = [];
        const stream = createReadStream(fileBuffer.path);

        // @ts-ignore
        stream.on("data", (chunk) => chunks.push(chunk));
        stream.on("end", () => resolve(Buffer.concat(chunks)));
        stream.on("error", reject);
      });
    } else {
      buffer = Buffer.from(body.fileBuffer);
    }
    let res = await this.ossFileService.uploadOssFile(fileName, buffer, type, user);
    if(type !=='count'){
      fs.unlinkSync(fileBuffer.path);
    }
    return { result: res, status: 200 };
  }
}